#include "ipc.h"
void provide()
{
	srand((unsigned) time(NULL)); //用时间做种，每次产生随机数不一样
	int choose;
	while(1){
		choose=rand() %3;	//生成一个选项
		switch(choose){
			case 0:
				P(TP_Psyn_sem);
				P(TP_Pmtx_sem);
				tobacco[0]='T';
				paper[0]='P';
				printf("%d供应商提供:烟草%c,纸张%c\n",getpid(),tobacco[0],paper[0]);
				V(TP_Pmtx_sem);
				V(TP_Csyn_sem);
			break;
			case 1:
				P(PG_Psyn_sem);
				P(PG_Pmtx_sem);
				glue[0]='G';
				paper[0]='P';
				printf("%d供应商提供:胶水%c,纸张%c\n",getpid(),glue[0],paper[0]);
				V(PG_Pmtx_sem);
				V(PG_Csyn_sem);	
			break;
			case 2:
				P(GT_Psyn_sem);
				P(GT_Pmtx_sem);
				glue[0]='G';
				tobacco[0]='T';
				printf("%d供应商提供:胶水%c,烟草%c\n",getpid(),glue[0],tobacco[0]);
				V(GT_Pmtx_sem);
				V(GT_Csyn_sem);	
			break;
		}
		sleep(rate);
	}
}
int main(int argc,char * argv[])
{
	//可在在命令行第一参数指定一个进程睡眠秒数,以调解进程执行速度
	if(argv[1] != NULL) rate = atoi(argv[1]);
	else rate = 1; //不指定为1秒
	signal(SIGINT,(sighandler_t)sigcat); //注册一个本进程处理键盘中断的函数
	//初始化同步机制
	ipc_init();
	int pid;
	int status;
	pid=fork();
	if(pid<0){
		perror("fork error!");
		exit(EXIT_FAILURE);
	}else if(pid==0){
		provide();
	}else{
		//waitpid(pid,&status,0);//等待子进程结束
		pid=fork();
		if(pid<0){
			perror("fork error!");
			exit(EXIT_FAILURE);
		}else if(pid==0){
			provide();
		}else{
			waitpid(pid,&status,0);//等待子进程结束
		}
	}
	return 0;
}
